package com.xiaowen.tool;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: yf-wenhao
 * Date: 17/10/23
 * Time: 上午10:57
 */
@Slf4j
public class DateUtil {

    /**
     * The constant dataFormat.
     */
    public static final SimpleDateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd");
    /**
     * The constant dataTimeFormat.
     */
    public static final SimpleDateFormat dataTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static final DateTimeFormatter simpleDateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public static final DateTimeFormatter dataTimeFormatDefault = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public static final DateTimeFormatter dateTimeFormat_YYMMDD = DateTimeFormatter.ofPattern("yyyyMMdd");

    

    public final static DecimalFormat df = new DecimalFormat("0.00");//格式化小数




    /**
     * Gets min date time.
     * 获取当天时间最小的时间
     * @return the min date time
     */
    public static String getMinDateTime() {
        LocalDateTime localDateTime = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
        return localDateTime.format(simpleDateTimeFormatter);
    }


    /**
     * * 获取现在时间
     * *
     * * @return返回字符串格式 yyyy-MM-dd HH:mm:ss
     * @return the string date
     */
    public static String getNowDateTime() {
        LocalDateTime localDateTime = LocalDateTime.now();
        return localDateTime.format(simpleDateTimeFormatter);
    }

    public static String getNowDateTime(DateTimeFormatter dateTimeFormatter) {
        LocalDateTime localDateTime = LocalDateTime.now();
        return localDateTime.format(dateTimeFormatter);
    }

    public static Integer getNowDateTimeInt(DateTimeFormatter dateTimeFormatter) {
        LocalDateTime localDateTime = LocalDateTime.now();
        String time = localDateTime.format(dateTimeFormatter);
        if(StringUtils.isEmpty(time)){
            return 0;
        }
        return Integer.valueOf(time);
    }



    /**
     * String to date date.
     *
     * @param dateTime the date time
     * @return the date
     * @author hero
     * @date 2018 -07-07 15:42:22
     */
    public static Date stringToDate(String dateTime) {
        LocalDateTime localDateTime = LocalDateTime.parse(dateTime, simpleDateTimeFormatter);
        Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
        return Date.from(instant);
    }

    public static Date stringToDateBySdf(String dateTime) {
        try {
            return dataTimeFormat.parse(dateTime);
        } catch (ParseException e) {
            log.error("parse date failed:{}", dateTime, e);
            return null;
        }
    }

    /**
     * Gets time by str.
     *
     * @param dataFormat the data format
     * @param lessonStr  the lesson str
     * @return the time by str
     */
    //根据valueType和缺省的defaultString获取时间串 ok~
    public static long getTimeByStr(SimpleDateFormat dataFormat, String lessonStr) {
        if (null == lessonStr || "".equals(lessonStr)) {
            return 0;
        }
        try {
            return dataFormat.parse(lessonStr).getTime();
        } catch (Exception e) {
            return 0;
        }
    }

    public static  String getTimeByStrDefault(Date date) {
        String result = null;
        try {
            Instant instant = date.toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
            result = localDateTime.format(dataTimeFormatDefault);
        }catch (Exception e){
            log.info(" data 转 string 出错 : {}", e);
        }
        return result;
    }


    /**
     * String to date 8 long.
     *
     * @param dateTime the date time
     * @return the long
     * @author hero
     * @date 2018 -07-07 15:42:22
     */
    public static long stringToLong(String dateTime) {
        try {
            LocalDateTime localDateTime = LocalDateTime.parse(dateTime, simpleDateTimeFormatter);
            Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
            return instant.getEpochSecond() * 1000;
        } catch (Exception e) {
            log.error(" stringToLong dateTime : {} 转换报错，错误原因是 ： {}", dateTime, e);
        }
        return 0;
    }


    public static long dateToLong(Date date) {
        return stringToLong(getTimeByStrDefault(date));
    }




    /**
     * Gets expire time.
     *
     * @return the expire time
     */
    public static Long getExpireTime() {
        LocalDateTime midnight = LocalDateTime.now().plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
        return ChronoUnit.SECONDS.between(LocalDateTime.now(), midnight);
    }


    /**
     * Gets expire time.
     *
     * @return the expire time
     */
    public static Long getExpireTime(String dateTime) {
        LocalDateTime midnight = LocalDateTime.parse(dateTime, simpleDateTimeFormatter);
        return ChronoUnit.SECONDS.between(midnight, LocalDateTime.now());
    }




    /**
     * Time plus time date.
     *
     * @param dateTime the date time
     * @param plus     the plus
     * @return the date
     * @author hero
     * @date 2018 -07-07 15:42:22
     */
    public static  String plusDay(String dateTime, Integer plus) {
        LocalDateTime localDateTime = LocalDateTime.parse(dateTime, simpleDateTimeFormatter).plusDays(plus);
        return localDateTime.format(simpleDateTimeFormatter);
    }


    public static  String plusHour(Date dateTime, Integer plus) {
        LocalDateTime localDateTime = LocalDateTime.parse(getTimeByStrDefault(dateTime), simpleDateTimeFormatter).plusHours(plus);
        return localDateTime.format(simpleDateTimeFormatter);
    }

    public static  Long plusHourToTime(Date dateTime, Integer plus) {
        LocalDateTime localDateTime = LocalDateTime.parse(getTimeByStrDefault(dateTime), simpleDateTimeFormatter).plusHours(plus);
        return DateUtil.stringToLong(localDateTime.format(simpleDateTimeFormatter));
    }


    public static  String plusDay(Date dateTime, Integer plus) {
        LocalDateTime localDateTime = LocalDateTime.parse(getTimeByStrDefault(dateTime), simpleDateTimeFormatter).plusDays(plus);
        return localDateTime.format(simpleDateTimeFormatter);
    }



    public static  String plusTime(Date dateTime, Integer plus) {
        LocalDateTime localDateTime = LocalDateTime.parse(getTimeByStrDefault(dateTime), simpleDateTimeFormatter).plusHours(plus);
        return localDateTime.format(simpleDateTimeFormatter);
    }



    /**
     * 秒转化为天小时分秒字符串
     *
     * @param seconds
     * @return String
     */
    public static String formatSeconds(long seconds) {
        String timeStr = seconds + "秒";
        if (seconds > 60) {
            long second = seconds % 60;
            long min = seconds / 60;
            timeStr = min + "分" + second + "秒";
            if (min > 60) {
                min = (seconds / 60) % 60;
                long hour = (seconds / 60) / 60;
                timeStr = hour + "小时" + min + "分" + second + "秒";
                if (hour > 24) {
                    hour = ((seconds / 60) / 60) % 24;
                    long day = (((seconds / 60) / 60) / 24);
                    timeStr = day + "天" + hour + "小时" + min + "分" + second + "秒";
                }
            }
        }
        return timeStr;
    }

    /**
     * 获取当前时间距离一天结束的剩余秒数
     *
     * @param currentDate
     * @return Integer
     */
    public static Integer getRemainSecondsOneDay(Date currentDate) {
        LocalDateTime midnight = LocalDateTime.ofInstant(currentDate.toInstant(),
                ZoneId.systemDefault()).plusDays(1).withHour(0).withMinute(0)
                .withSecond(0).withNano(0);
        LocalDateTime currentDateTime = LocalDateTime.ofInstant(currentDate.toInstant(),
                ZoneId.systemDefault());
        long seconds = ChronoUnit.SECONDS.between(currentDateTime, midnight);
        return (int) seconds;
    }

    /**
     * @param d 字符串原值(数字字符)
     * @return int 返回100倍的整数原值
     * @Description: double类型字符串保留2位小数返回其100倍整数原值
     * @author
     * @date 2018年10月19日 19:04:06
     */
    public static
    int getIntegerFromDoubleString(String d) {
        if ("0".equals(d) || "".equals(d)) {
            return 0;
        }
        BigDecimal b = new BigDecimal(d).setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal bd = new BigDecimal(b.doubleValue() * 100).setScale(0, BigDecimal.ROUND_HALF_UP);
        return Integer.parseInt(bd.toString());
    }

    public static Double getRatioByInteger(Integer d1,Integer d2)
    {
        if(null == d1 || null == d2 || 0 == d1)
        {
            return 0.00;
        }
        try{
            return Double.valueOf(df.format((double)(d2)/d1));
        }catch(Exception e)
        {
            return 0.00;
        }
    }
}
